package com.logistics.security;

import com.logistics.common.SiteContextHolder;
import com.logistics.common.TenantContextHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT 认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    private final JwtTokenProvider jwtTokenProvider;
    
    public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
        this.jwtTokenProvider = jwtTokenProvider;
    }
    
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            // 获取 Token
            String token = getTokenFromRequest(request);
            
            System.out.println("JWT Filter - Token: " + (token != null ? token.substring(0, 20) + "..." : "null"));
            
            if (StringUtils.hasText(token)) {
                boolean isValid = jwtTokenProvider.validateToken(token);
                System.out.println("JWT Filter - Token valid: " + isValid);
                
                if (isValid) {
                    // 从 Token 中获取信息
                    Long userId = jwtTokenProvider.getUserIdFromToken(token);
                    Long tenantId = jwtTokenProvider.getTenantIdFromToken(token);
                    Long siteId = jwtTokenProvider.getSiteIdFromToken(token);
                    String username = jwtTokenProvider.getUsernameFromToken(token);
                    String role = jwtTokenProvider.getRoleFromToken(token);
                    
                    System.out.println("JWT Filter - UserId: " + userId + ", TenantId: " + tenantId + ", SiteId: " + siteId + ", Role: " + role);
                    
                    // 设置租户ID和站点ID到 ThreadLocal
                    TenantContextHolder.setTenantId(tenantId);
                    SiteContextHolder.setSiteId(siteId);
                    
                    // 设置 userId 到 request attributes，供 Controller 使用
                    request.setAttribute("userId", userId);
                    request.setAttribute("tenantId", tenantId);
                    request.setAttribute("siteId", siteId);
                    request.setAttribute("username", username);
                    request.setAttribute("role", role);
                    
                    // 构造权限集合：包含角色与权限点
                    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                    if (StringUtils.hasText(role)) {
                        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
                    }
                    List<String> perms = jwtTokenProvider.getPermissionsFromToken(token);
                    if (perms != null) {
                        for (String p : perms) {
                            if (StringUtils.hasText(p)) {
                                authorities.add(new SimpleGrantedAuthority(p));
                            }
                        }
                    }
                    
                    // 设置认证信息到 Spring Security 上下文
                    UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(
                            userId,
                            null,
                            authorities
                        );
                    
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    System.out.println("JWT Filter - Authentication set successfully");
                }
            }
            
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            System.err.println("JWT Filter Error: " + e.getMessage());
            e.printStackTrace();
            filterChain.doFilter(request, response);
        } finally {
            // 清除 ThreadLocal，避免内存泄漏
            TenantContextHolder.clear();
            SiteContextHolder.clear();
        }
    }
    
    /**
     * 从请求头中获取 Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}

